/*
 * 定时任务调度器
 * 用于执行定时任务的基础类
 */
package com.ruoyi.binding.job;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.binding.domain.JDP.Params.JDPProOrderParam;
import com.ruoyi.binding.domain.JDP.Tools.OkHttpSessionClient;
import com.ruoyi.binding.domain.MhBinding;
import com.ruoyi.binding.domain.MhUserGameDispatchConfig;
import com.ruoyi.binding.domain.MhUserGamePrice;
import com.ruoyi.binding.mapper.MhUserGameDispatchConfigMapper;
import com.ruoyi.binding.service.IMhBindingService;
import com.ruoyi.binding.service.IMhJDPService;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.quartz.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class DispatchJob implements Job {

    /*
     * 执行定时任务的方法
     * @param context 任务执行上下文，包含任务相关数据
     * @throws JobExecutionException 任务执行异常
     * 获取任务ID并记录日志，然后执行具体的业务逻辑
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        Long taskId = context.getMergedJobDataMap().getLong("taskId");
        log.info("【定时任务执行】任务ID：{} 派单任务开始执行...", taskId);
        // TODO: 在这里调用你自己的业务逻辑，比如：

        // 获取Spring中的Mapper和服务
        MhUserGameDispatchConfigMapper configMapper = SpringUtils.getBean(MhUserGameDispatchConfigMapper.class);
        IMhJDPService jdpService = SpringUtils.getBean(IMhJDPService.class);
        OkHttpSessionClient sessionClient = SpringUtils.getBean(OkHttpSessionClient.class);
        IMhBindingService bindingService = SpringUtils.getBean(IMhBindingService.class);

        // 查出任务配置
        MhUserGameDispatchConfig config = configMapper.selectMhUserGameDispatchConfigByTaskId(taskId);
        if (config == null) {
            log.error("任务ID={} 未找到派单配置", taskId);
            return;
        }
        // 指定用户ID


        jdpService.setUserId(config.getUserId());

        //查询管理员抽成
        MhBinding mhBinding = bindingService.selectMhBindingByUserId(config.getUserId());
        BigDecimal adminRatio = new BigDecimal("0.0");
        for (MhUserGamePrice price : mhBinding.getMhUserGamePriceList()) {
            // 根据游戏名匹配（忽略大小写和空格差异，可选）
            if (price.getGameCategoryName().trim().equalsIgnoreCase(config.getGameName().trim())) {
                adminRatio = price.getPriceRatio();
                break;
            }
        }
        log.info("管理员抽成比例: {}%", adminRatio);

// 查询用户抽成
        BigDecimal userRatio = config.getUserPriceRatio();
        log.info("用户抽成比例: {}%", userRatio);

//       计算订单抽成比例 原价*(1-adminRatio)*(1-userRatio)
        // 转换为系数
        BigDecimal adminFactor = BigDecimal.ONE.subtract(adminRatio.divide(BigDecimal.valueOf(100)));
        BigDecimal userFactor = BigDecimal.ONE.subtract(userRatio.divide(BigDecimal.valueOf(100)));

// 综合抽成系数：原价 * 这个系数 = 最终金额
        BigDecimal combinedFactor = adminFactor.multiply(userFactor).setScale(4, BigDecimal.ROUND_HALF_UP);

        log.info("综合抽成系数: {}", combinedFactor); // 例如0.7200


        //查询游戏任务列表
        JDPProOrderParam param = new JDPProOrderParam();
        param.setGameName(config.getGameName());
        JSONObject allOrders = jdpService.queryInsideRecOrder(param);
        log.info("【定时任务执行】任务ID：{} 查询游戏{} 返回 {}", taskId, config.getGameName(), allOrders);

        int batchSize = 8;
        JSONArray dataArray = allOrders.getJSONArray("data");
        // 分批发送到webhook
        int totalBatches = dataArray.size() / batchSize + (dataArray.size() % batchSize == 0 ? 0 : 1);
        String[] webhooks = config.getWebhookUrls().split(",");
        for (int batchNum = 0; batchNum < totalBatches; batchNum++) {
            int start = batchNum * batchSize;
            int end = Math.min((batchNum + 1) * batchSize, dataArray.size());

            JSONArray batch = new JSONArray();
            for (int i = start; i < end; i++) {
                batch.add(dataArray.getJSONObject(i));
            }

            StringBuilder msgContent = new StringBuilder();
            for (int i = 0; i < batch.size(); i++) {
                JSONObject order = batch.getJSONObject(i);
                Object recFeeObj = order.get("recFee");
                if (recFeeObj == null) {
                    throw new IllegalArgumentException("订单 recFee 为空，无法计算抽成价格");
                }

// 推荐先把它转成字符串再转 BigDecimal，兼容 int/long/double 等类型
                BigDecimal recFee = new BigDecimal(recFeeObj.toString());

// 计算抽成后的最终价格
                BigDecimal finalPrice = recFee.multiply(combinedFactor).setScale(2, BigDecimal.ROUND_HALF_UP);
                log.info("订单原价 recFee={}，综合抽成系数={}，最终价格 finalPrice={}", recFee, combinedFactor, finalPrice);
                if (Objects.equals(config.getMsgType(), "markdown")) {
                    msgContent.append("**订单号**:<font color=\"comment\">").append(order.get("orderIdView")).append("</font>\n")
                            .append("**游戏名**:<font color=\"info\">").append(order.get("gameName")).append("</font>\n")
                            .append("**发单价**:<font color=\"warning\">").append(finalPrice).append("</font>\n")
                            .append("**任务内容**:").append(order.get("project")).append("\n----------------------\n\n");
                } else if (Objects.equals(config.getMsgType(), "text")) {
                    msgContent.append("订单号:").append(order.get("orderIdView")).append("\n")
                            .append("游戏名:").append(order.get("gameName")).append("\n")
                            .append("发单价:").append(finalPrice).append("\n")
                            .append("任务内容:").append(order.get("project")).append("\n----------------------\n\n");
                }
            }

            JSONObject wxMsg = new JSONObject()
                    .fluentPut("msgtype", config.getMsgType())
                    .fluentPut(config.getMsgType(), new JSONObject().fluentPut("content", msgContent));

            String webhookUrl = webhooks[batchNum % webhooks.length].trim();
            try (Response wxResp = sessionClient.postJson(webhookUrl, wxMsg)) {
                String responseStr = wxResp.body() != null ? wxResp.body().string() : "无返回内容";
                log.info("任务ID={} 批次 {}/{} 已发送到webhook={} 响应:{}", taskId, batchNum + 1, totalBatches, webhookUrl, responseStr);
            } catch (IOException e) {
                log.error("任务ID={} 发送webhook异常", taskId, e);
            }
        }
        log.info("【定时任务执行】任务ID：{} 派单任务结束...", taskId);
        log.info("任务ID={}执行完毕", taskId);
        log.info("下次执行时间{}", context.getNextFireTime());
    }

}
